/* HttpMethodServlet.java
 * 
 * class HttpMethodServlet
 */

package presentation;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import exceptions.LogWriter;

import presentation.controller.HttpBaseController;
import presentation.controller.Redirect;

/**
 * class HttpMethodServlet
 * 
 * servlet forwarding all requests to the according requests handler
 * 
 * 
 */

public class HttpMethodServlet extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 1L;

	/**
	 * handler for get methods
	 * 
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpBaseController controller = getHttpController(request, response);

		controller.process();
	}

	/**
	 * handler for post methods
	 * 
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpBaseController controller = getHttpController(request, response);

		controller.process();
	}

	/**
	 * method to get the responsible action controller for the request
	 */
	private HttpBaseController getHttpController(HttpServletRequest request, HttpServletResponse response) {
		String name = request.getParameter("action");

		Class controller = null;
		HttpBaseController instance = null;

		try {
			controller = Class.forName("presentation.controller." + name);
			instance = (HttpBaseController) controller.newInstance();
			instance.setRequest(request);
			instance.setResponse(response);
			instance.setServletContext(this.getServletContext());
			instance.setArguments(getArguments(request));
		} catch (Exception e) {
			new LogWriter().write(e);
			
			instance = new Redirect();
			instance.setRequest(request);
			instance.setResponse(response);
			instance.setServletContext(this.getServletContext());
			instance.setArguments(getArguments(request));
		}
		return instance;
	}



	/**
	 * method saving all request name/value pairs in a hashtable
	 */
	private Hashtable<String, String> getArguments(HttpServletRequest request) {
		Hashtable<String, String> arguments = new Hashtable<String, String>();
		String key = null;
		Enumeration parameterNames = request.getParameterNames();

		while (parameterNames.hasMoreElements() == true) {
			key = (String) parameterNames.nextElement();
			arguments.put(key, request.getParameter(key));
		}

		return arguments;
	}

}// HttpMethodServlet

/* end of HttpMethodServlet.java */

